<template>
  <template
    v-if="
      props.icon && (props.icon.includes('http') || props.icon.startsWith('/'))
    "
  >
    <img
      :class="iconClass"
      :style="{ fontSize: iconSize }"
      v-bind="$attrs"
      :src="props.icon"
      @click="(e: MouseEvent) => handleClick(e)"
    />
  </template>
  <template v-else-if="props.icon && props.icon.includes(':')">
    <Icon
      :class="iconClass"
      :style="{ fontSize: iconSize }"
      v-bind="$attrs"
      :icon="props.prefix ? `@${props.prefix}:${props.icon}` : props.icon"
      :color="props.color"
      @click="(e: MouseEvent) => handleClick(e)"
    />
  </template>
  <template v-else>
    <svg
      :class="iconClass"
      :style="{ fontSize: iconSize, color: props.color }"
      v-bind="$attrs"
      @click="(e: MouseEvent) => handleClick(e)"
    >
      <use :xlink:href="`#icon-${props.icon}`" fill="color" />
    </svg>
  </template>
</template>

<script lang="ts" setup>
import { computed } from "vue";
import { Icon } from "@iconify/vue";

export interface ISvgIconProp {
  class?: string;
  icon: string;
  color?: string;
  size?: number | string;
  disabled?: boolean;
  prefix?: string; // iconify 前缀
}
const props = withDefaults(defineProps<ISvgIconProp>(), {
  class: "",
  color: undefined,
  size: undefined,
  disabled: false,
});
const iconClass = computed(() => {
  let classStr = "svg-icon";
  if (props.class) {
    classStr += ` ${props.class}`;
  }
  if (props.disabled) {
    classStr += ` disabled-svg`;
  }
  return classStr;
});

const iconSize = computed(() => {
  if (props.size !== undefined) {
    return Number.isNaN(props.size) ? props.size : `${props.size}px`;
  }
  return undefined;
});

const emits = defineEmits(["click"]);
function handleClick(e: MouseEvent) {
  if (!props.disabled) {
    emits("click", e);
  }
}
</script>

<style scoped>
.svg-icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.125em;
  fill: currentColor;
  overflow: hidden;
  position: relative;
}
.svg-icon.disabled-svg,
.svg-icon.disabled-svg:focus,
.svg-icon.disabled-svg:hover {
  opacity: 0.5;
  cursor: not-allowed;
}
</style>
